<template>
  <div class="global-box">
    <a-form-model
      class="APP"
      ref="APPForm"
      :model="APPForm"
      :rules="APPFormRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-model-item label="商品名称"> {{ APPForm.name }} </a-form-model-item>
      <a-form-model-item label="所属app" prop="toApp" :wrapper-col="{ span: 6 }">
        <a-select mode="multiple" v-model="APPForm.toApp" placeholder="请选择所属app">
          <a-select-option :value="item.appId" :key="item.appId" v-for="item in appList">{{
            item.appName
          }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="是否关联图书">
        <a-radio-group v-model="APPForm.books">
          <a-radio :value="item.value" :key="item.value" v-for="item in bookList">{{
            item.label
          }}</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="套餐封面图片">
        <a-upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :customRequest="handleChange"
          :before-upload="beforeUpload"
        >
          <img v-if="APPForm.cover" :src="imageUrl + APPForm.cover" alt="avatar" />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        <span style="color: #ccc">只能上传jpg/jpeg/png文件，尺寸750*422像素</span>
      </a-form-model-item>
      <a-form-model-item label="授课师资">
        <a @click="addTeacher">添加师资</a>
        <a-table
          v-if="teacherData && teacherData.length > 0"
          :columns="columns"
          :data-source="teacherData"
          :pagination="false"
          :rowKey="(record, index) => index"
        >
          <span slot="cover" slot-scope="text, record">
            <template>
              <img :src="imageUrl + record.cover" alt="avatar" />
            </template>
          </span>
          <span slot="sex" slot-scope="text, record">
            <template>
              {{ record.sex === 0 ? '男' : '女' }}
            </template>
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleDelete(record)">删除</a>
            </template>
          </span>
        </a-table>
      </a-form-model-item>
      <a-form-model-item label="名师介绍">
        <div id="introduce"></div>
      </a-form-model-item>
      <a-form-model-item label="课程大纲">
        <div id="outline"></div>
      </a-form-model-item>
      <a-form-model-item label="课程介绍">
        <div id="desc"></div>
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 14, offset: 5 }">
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </a-form-model-item>
    </a-form-model>
    <a-modal
      title="新增师资"
      :visible="addVisible"
      @ok="addHandleOk"
      @cancel="addVisible = false"
      okText="提交"
      cancelText="取消"
      width="25%"
    >
      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="addFormRules"
        :label-col="addLabelCol"
        :wrapper-col="addWrapperCol"
      >
        <a-form-model-item label="师资姓名" prop="name">
          <a-input placeholder="请输入师资姓名" v-model="addForm.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="师资性别" prop="sex">
          <a-select v-model="addForm.sex" placeholder="请选择师资性别">
            <a-select-option :value="item.value" :key="item.value" v-for="item in sexList">{{
              item.label
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="师资头像" prop="courseStatus">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="addBeforeUpload"
            :customRequest="addHandleChange"
          >
            <img v-if="addForm.cover" :src="imageUrl + addForm.cover" alt="avatar" />
            <div v-else>
              <a-icon :type="loadingT ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
          <span style="color: #ccc">只能上传jpg/jpeg/png文件</span>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { getApp, appInfo, upload, appSave } from '@/api/product/goods'
import E from 'wangeditor'
const columns = [
  {
    title: '头像',
    dataIndex: 'cover',
    scopedSlots: { customRender: 'cover' },
    align: 'center'
  },
  {
    title: '师资姓名',
    dataIndex: 'name',
    align: 'center'
  },
  {
    title: '性别',
    dataIndex: 'sex',
    scopedSlots: { customRender: 'sex' },
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]
export default {
  data () {
    return {
      columns,
      teacherData: [],
      addVisible: false,
      APPForm: {
        name: '',
        toApp: [],
        books: 1,
        cover: '',
        isAdd: true
      },
      appList: [],
      loading: false,
      loadingT: false,
      bookList: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ],
      labelCol: { span: 3 },
      wrapperCol: { span: 18 },
      addLabelCol: { span: 6 },
      addWrapperCol: { span: 15 },
      APPFormRules: {
        toApp: [
          { required: true, message: '请选择所属app', trigger: 'change' }
        ]
      },
      addForm: {
        name: '',
        sex: undefined,
        cover: ''
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入师资姓名', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择师资性别', trigger: 'change' }
        ]
      },
      sexList: [
        {
          label: '男',
          value: 0
        },
        {
          label: '女',
          value: 1
        }
      ],
      packageId: '',
      imageUrl: 'https://product.zhongyewx.com.cn/',
      introduce: '',
      outline: '',
      desc: ''
    }
  },
  mounted () {
    this.initE()
    if (this.$route.params.packageId) {
      this.packageId = this.$route.params.packageId
      this.getData()
    }
  },
  methods: {
    initE () {
      this.introduce = new E(document.getElementById('introduce'))
      this.introduce.create()
      this.outline = new E(document.getElementById('outline'))
      this.outline.create()
      this.desc = new E(document.getElementById('desc'))
      this.desc.create()
    },
    getData () {
      const data = {
        packageId: this.packageId
      }
      getApp({}).then(res => {
        if (res.code === '1') {
          this.appList = res.data
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
      appInfo(data).then(res => {
        if (res.code === '1') {
          this.APPForm.name = res.data.packageName
          this.APPForm.isAdd = res.data.isAdd
          this.APPForm.toApp = res.data.appIds || []
          this.APPForm.cover = res.data.imageUrl || ''
          this.APPForm.books = res.data.isRelatedBooks
          this.packageId = res.data.packageId || ''
          this.teacherData = []
          if (res.data.packageTitle && res.data.packageTitle !== '') {
            this.introduce.txt.html(res.data.packageTitle)
          }
          if (res.data.courseOutline && res.data.courseOutline !== '') {
            this.outline.txt.html(res.data.courseOutline)
          }
          if (res.data.description && res.data.description !== '') {
            this.desc.txt.html(res.data.description)
          }
          for (let i = 0; i < 6; i++) {
            this.teacherData.push({
              name: '',
              sex: '',
              cover: ''
            })
          }
          if (res.data.packageTeacherOne) {
            this.teacherData[0].name = res.data.packageTeacherOne
          }
          if (res.data.packageTeacherTwo) {
            this.teacherData[1].name = res.data.packageTeacherTwo
          }
          if (res.data.packageTeacherThree) {
            this.teacherData[2].name = res.data.packageTeacherThree
          }
          if (res.data.packageTeacherFour) {
            this.teacherData[3].name = res.data.packageTeacherFour
          }
          if (res.data.packageTeacherFive) {
            this.teacherData[4].name = res.data.packageTeacherFive
          }
          if (res.data.packageTeacherSix) {
            this.teacherData[5].name = res.data.packageTeacherSix
          }
          if (res.data.teacherOneSex) {
            this.teacherData[0].sex = res.data.teacherOneSex
          }
          if (res.data.teacherTwoSex) {
            this.teacherData[1].sex = res.data.teacherTwoSex
          }
          if (res.data.teacherThreeSex) {
            this.teacherData[2].sex = res.data.teacherThreeSex
          }
          if (res.data.teacherFourSex) {
            this.teacherData[3].sex = res.data.teacherFourSex
          }
          if (res.data.teacherFiveSex) {
            this.teacherData[4].sex = res.data.teacherFiveSex
          }
          if (res.data.teacherSixSex) {
            this.teacherData[5].sex = res.data.teacherSixSex
          }
          if (res.data.teacherImageOne) {
            this.teacherData[0].cover = res.data.teacherImageOne
          }
          if (res.data.teacherImageTwo) {
            this.teacherData[1].cover = res.data.teacherImageTwo
          }
          if (res.data.teacherImageThree) {
            this.teacherData[2].cover = res.data.teacherImageThree
          }
          if (res.data.teacherImageFour) {
            this.teacherData[3].cover = res.data.teacherImageFour
          }
          if (res.data.teacherImageFive) {
            this.teacherData[4].cover = res.data.teacherImageFive
          }
          if (res.data.teacherImageSix) {
            this.teacherData[5].cover = res.data.teacherImageSix
          }
          this.teacherData = this.teacherData.filter(item => {
            return item.name !== ''
          })
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 限制上传图片尺寸 700*422
    isSize (file, width, height) {
      const self = this
      return new Promise(function (resolve, reject) {
        const filereader = new FileReader()
        filereader.onload = (e) => {
          const src = e.target.result
          const image = new Image()
          image.onload = function () {
            if (
              (width && this.width > width) ||
              (height && this.height > height)
            ) {
              self.$message.error(
                '请上传按' + width + '*' + height + '等比缩放的图片'
              )
              // reject()
            } else {
              resolve()
            }
          }
          image.onerror = reject
          image.src = src
        }
        filereader.readAsDataURL(file)
      })
    },
    // 套餐封面图片上传
    handleChange (info) {
      this.loading = true
      const formdata = new FormData()
      formdata.append('file', info.file)
      upload(formdata).then(res => {
        if (res.code === '1') {
          res.data.path = res.data.path.replace('/ShareDisk', '')
          this.APPForm.cover = res.data.path
          this.loading = false
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 套餐封面上传前的验证
    beforeUpload (file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('暂不支持此文件类型')
      }
      return isJpgOrPng && this.isSize(file, 700, 422)
    },
    // 添加师资
    addTeacher () {
      if (this.teacherData.length >= 6) {
        this.$message.error('最多可添加六位老师')
        return false
      }
      this.addForm = {
        name: '',
        sex: undefined,
        cover: ''
      }
      this.addVisible = true
    },
    // 师资头像图片上传
    addHandleChange (info) {
      this.loadingT = true
      const formdata = new FormData()
      formdata.append('file', info.file)
      upload(formdata).then(res => {
        if (res.code === '1') {
          res.data.path = res.data.path.replace('/ShareDisk', '')
          this.addForm.cover = res.data.path
          this.loadingT = false
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 师资头像上传前的验证
    addBeforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isJpgOrPng) {
        this.$message.error('请选择正确的图片格式')
      }
      return isJpgOrPng && this.isSize(file, 750, 750)
    },
    // 提交
    onSubmit () {
      const txt = '<p><br></p>'
      const data = {
        appId: this.APPForm.toApp.join(),
        isAdd: this.APPForm.isAdd,
        isRelatedBooks: this.APPForm.books,
        packageId: this.packageId
      }
      if (this.introduce.txt.html() !== txt) {
        data.packageTitle = this.introduce.txt.html()
      }
      if (this.outline.txt.html() !== txt) {
        data.courseOutline = this.outline.txt.html()
      }
      if (this.desc.txt.html() !== txt) {
        data.description = this.desc.txt.html()
      }
      if (this.APPForm.cover) {
        data.imageUrl = this.APPForm.cover
      }
      if (this.teacherData[0]) {
        data.packageTeacherOne = this.teacherData[0].name
      }
      if (this.teacherData[1]) {
        data.packageTeacherTwo = this.teacherData[1].name
      }
      if (this.teacherData[2]) {
        data.packageTeacherThree = this.teacherData[2].name
      }
      if (this.teacherData[3]) {
        data.packageTeacherFour = this.teacherData[3].name
      }
      if (this.teacherData[4]) {
        data.packageTeacherFive = this.teacherData[4].name
      }
      if (this.teacherData[5]) {
        data.packageTeacherSix = this.teacherData[5].name
      }
      if (this.teacherData[0]) {
        data.teacherOneSex = this.teacherData[0].sex
      }
      if (this.teacherData[1]) {
        data.teacherTwoSex = this.teacherData[1].sex
      }
      if (this.teacherData[2]) {
        data.teacherThreeSex = this.teacherData[2].sex
      }
      if (this.teacherData[3]) {
        data.teacherFourSex = this.teacherData[3].sex
      }
      if (this.teacherData[4]) {
        data.teacherFiveSex = this.teacherData[4].sex
      }
      if (this.teacherData[5]) {
        data.teacherSixSex = this.teacherData[5].sex
      }
      if (this.teacherData[0]) {
        data.teacherImageOne = this.teacherData[0].cover
      }
      if (this.teacherData[1]) {
        data.teacherImageTwo = this.teacherData[1].cover
      }
      if (this.teacherData[2]) {
        data.teacherImageThree = this.teacherData[2].cover
      }
      if (this.teacherData[3]) {
        data.teacherImageFour = this.teacherData[3].cover
      }
      if (this.teacherData[4]) {
        data.teacherImageFive = this.teacherData[4].cover
      }
      if (this.teacherData[5]) {
        data.teacherImageSix = this.teacherData[5].cover
      }
      this.$refs.APPForm.validate(valid => {
        if (valid) {
          appSave(data).then(res => {
            if (res.code === '1') {
              this.$router.push({
                name: 'goods'
              })
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error(err.msg)
          })
        } else {
          return false
        }
      })
    },
    // 表格删除
    handleDelete (re) {
      this.teacherData = this.teacherData.filter(item => {
        return item.name !== re.name
      })
    },
    // 新增师资 提交
    addHandleOk () {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.addVisible = false
          this.teacherData.push(this.addForm)
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.APP {
  margin-top: 30px;
}
</style>
<style lang="less">
.w-e-menu {
  z-index: 2 !important;
}
.w-e-text-container {
  z-index: 1 !important;
}
</style>
